<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="主题ID" prop="topicId">
        <el-input v-model="queryParams.topicId" placeholder="请输入热搜主题ID" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="配置ID" prop="configId">
        <el-input v-model="queryParams.configId" placeholder="请输入配置ID" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="虚构等级" prop="fictionLevel">
      <el-select v-model="queryParams.fictionLevel" placeholder="请选择虚构等级" clearable style="width:220px">
          <el-option label="基于事实" :value="0" />
          <el-option label="部分虚构" :value="1" />
          <el-option label="完全虚构" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="MagicStick" :loading="analyzing && !isMinimized" :disabled="analyzing && !isMinimized" @click="handleAutoAnalyze">
          {{ getAnalyzeButtonText() }}
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="digestList" @selection-change="handleSelectionChange" style="width: 100%;" max-height="600px">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主题ID" align="center" prop="topicId" width="60" />
      <el-table-column label="配置ID" align="center" prop="configId" width="60" />
      <el-table-column label="标题" align="center" prop="generatedTitle" width="130" show-overflow-tooltip />
      <el-table-column label="概要" align="center" prop="summaryContent" width="150" show-overflow-tooltip />
      <el-table-column label="生成文章" align="center" prop="generatedArticle" width="120" show-overflow-tooltip />
      <el-table-column label="关键词" align="center" prop="keywords" width="120" show-overflow-tooltip />
      <el-table-column label="文章数" align="center" prop="articleCount" width="80" />
      <el-table-column label="虚构等级" align="center" prop="fictionLevel" width="100">
        <template #default="scope">
          {{ getFictionLevelText(scope.row.fictionLevel) }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="generationStatus" width="100">
        <template #default="scope">
          {{ getGenerationStatusText(scope.row.generationStatus) }}
        </template>
      </el-table-column>
      <el-table-column label="质量评分" align="center" prop="qualityScore" width="80" />
      <el-table-column label="操作" align="center" width="180" fixed="right">
        <template #default="scope">
          <el-button link type="primary" @click="handleViewDetail(scope.row)">详情</el-button>
          <el-button link type="primary" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="800px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="主题ID" prop="topicId">
              <el-input v-model="form.topicId" placeholder="请输入热搜主题ID" :disabled="!!form.id"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="配置ID" prop="configId">
              <el-input v-model="form.configId" placeholder="请输入配置ID" :disabled="!!form.id"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关键词" prop="keywords">
              <el-input v-model="form.keywords" placeholder="请输入关键词，逗号分隔" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="文章数量" prop="articleCount">
              <el-input-number v-model="form.articleCount" :min="0" :disabled="!!form.id"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="虚构等级" prop="fictionLevel" >
              <el-select v-model="form.fictionLevel" placeholder="请选择虚构等级" :disabled="!!form.id" style="width:220px">
                <el-option label="基于事实" :value="0" />
                <el-option label="部分虚构" :value="1" />
                <el-option label="完全虚构" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="质量评分" prop="qualityScore">
              <el-input-number v-model="form.qualityScore" :min="0" :max="100" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="概要内容" prop="summaryContent">
          <el-input v-model="form.summaryContent" type="textarea" :rows="4" maxlength="2000" show-word-limit />
        </el-form-item>

        <el-form-item label="文章内容" prop="generatedArticle">
          <el-input v-model="form.generatedArticle" type="textarea" :rows="6" maxlength="5000" show-word-limit />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog title="查看详情" v-model="detailVisible" width="800px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="主题ID">{{ currentRow.topicId }}</el-descriptions-item>
        <el-descriptions-item label="配置ID">{{ currentRow.configId }}</el-descriptions-item>
        <el-descriptions-item label="关键词">{{ currentRow.keywords }}</el-descriptions-item>
        <el-descriptions-item label="文章数量">{{ currentRow.articleCount }}</el-descriptions-item>
        <el-descriptions-item label="虚构等级">{{ getFictionLevelText(currentRow.fictionLevel) }}</el-descriptions-item>
        <el-descriptions-item label="质量评分">{{ currentRow.qualityScore }}</el-descriptions-item>
      </el-descriptions>
      
      <el-divider>概要内容</el-divider>
      <div class="content-box">{{ currentRow.summaryContent }}</div>
      
      <el-divider>文章内容</el-divider>
      <div class="content-box">{{ currentRow.generatedArticle }}</div>
    </el-dialog>

    <!-- 分析结果对话框 -->
    <el-dialog title="AI分析结果" v-model="analysisVisible" width="500px">
      <el-result :icon="analysisResult.success ? 'success' : 'error'" :title="analysisResult.message">
        <template #sub-title v-if="analysisResult.data">
          <p>总数量: {{ analysisResult.data.totalCount || 0 }}</p>
          <p>成功: {{ analysisResult.data.successCount || 0 }}</p>
          <p>失败: {{ analysisResult.data.failCount || 0 }}</p>
          <p>耗时: {{ analysisResult.data.duration || 0 }}ms</p>
        </template>
      </el-result>
    </el-dialog>

    <!-- 分析进度对话框 -->
    <el-dialog title="AI分析进度" v-model="progressVisible" width="500px" :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false">
      <template #header="{ close, titleId, titleClass }">
        <div class="dialog-header">
          <span :id="titleId" :class="titleClass">AI分析进度</span>
          <div class="dialog-header-buttons">
            <el-button type="text" @click="handleMinimize" title="最小化">
              <el-icon><Minus /></el-icon>
            </el-button>
            <el-button type="text" @click="handleStopAnalysis" title="停止分析" :disabled="!canStop">
              <el-icon><Close /></el-icon>
            </el-button>
          </div>
        </div>
      </template>
      <div class="progress-container">
        <el-progress :percentage="progressData.percentage" :status="progressData.status"></el-progress>
        <div class="progress-info">
          <p>状态: {{ progressData.statusText }}</p>
          <p>总数量: {{ progressData.totalCount }}</p>
          <p>已处理: {{ progressData.processedCount }} / {{ progressData.totalCount }}</p>
          <p>成功: {{ progressData.successCount }}</p>
          <p>失败: {{ progressData.failureCount }}</p>
          <p>当前处理: {{ progressData.currentProcessing }}</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Digest">
import { listDigest, getDigest, delDigest, addDigest, updateDigest, autoAnalyzeAllTopics, getAnalysisProgress ,stopAnalysisTask  } from "@/api/digest/digest";
import { Minus, Close } from '@element-plus/icons-vue';
const { proxy } = getCurrentInstance();

// 响应式数据
const digestList = ref([]);
const dialogVisible = ref(false);
const detailVisible = ref(false);
const analysisVisible = ref(false);
const currentRow = ref({});
const loading = ref(true);
const analyzing = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const analysisResult = ref({ success: false, message: '', data: null });

// 进度对话框控制
const isMinimized = ref(false);
const canStop = ref(true); // 是否可以停止分析

// 进度相关数据
const progressVisible = ref(false);
const progressData = ref({
  percentage: 0,
  status: '',
  statusText: '准备中',
  totalCount: 0,
  processedCount: 0,
  successCount: 0,
  failureCount: 0,
  currentProcessing: '',
  taskId: ''
});
const progressTimer = ref(null);

// 表单数据
const form = ref({});
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  topicId: null,
  configId: null,
  fictionLevel: null,
});

// 表单验证规则
const rules = {
  topicId: [{ required: true, message: "主题ID不能为空", trigger: "blur" }],
  configId: [{ required: true, message: "配置ID不能为空", trigger: "blur" }],
  summaryContent: [{ required: true, message: "概要内容不能为空", trigger: "blur" }],
  generatedArticle: [{ required: true, message: "文章内容不能为空", trigger: "blur" }],
  fictionLevel: [{ required: true, message: "虚构等级不能为空", trigger: "change" }],
};

// 计算属性
const dialogTitle = computed(() => form.value.id ? '修改' : '新增');

// 方法
const getList = () => {
  loading.value = true;
  listDigest(queryParams.value).then(response => {
    digestList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
};

const resetForm = () => {
  form.value = {};
  proxy.resetForm("formRef");
};

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = () => {
  proxy.resetForm("queryRef");
  handleQuery();
};

const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

const handleAdd = () => {
  resetForm();
  dialogVisible.value = true;
};

const handleUpdate = (row) => {
  resetForm();
  const id = row?.id || ids.value[0];
  if (row?.id) {
    form.value = { ...row };
    dialogVisible.value = true;
  } else {
    getDigest(id).then(response => {
      form.value = response.data;
      dialogVisible.value = true;
    });
  }
};

const submitForm = () => {
  proxy.$refs.formRef.validate(valid => {
    if (valid) {
      const api = form.value.id ? updateDigest : addDigest;
      api(form.value).then(() => {
        proxy.$modal.msgSuccess(form.value.id ? "修改成功" : "新增成功");
        dialogVisible.value = false;
        getList();
      });
    }
  });
};

const handleDelete = (row) => {
  const deleteIds = row?.id || ids.value;
  proxy.$modal.confirm(`确认删除选中的数据项？`).then(() => {
    return delDigest(deleteIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  });
};

const handleViewDetail = (row) => {
  currentRow.value = row;
  detailVisible.value = true;
};

const handleAutoAnalyze = () => {
  // 检查是否有最小化的任务，如果有则直接显示进度
  if (isMinimized.value && analyzing.value && progressData.value.taskId) {
    progressVisible.value = true;
    isMinimized.value = false;
    return;
  }
  
  // 如果正在分析中，直接显示进度
  if (analyzing.value && progressData.value.taskId) {
    progressVisible.value = true;
    return;
  }

  proxy.$modal.confirm('确认对所有未处理的主题进行AI分析？').then(() => {
    analyzing.value = true;
    // 重置进度数据
    progressData.value = {
      percentage: 0,
      status: '',
      statusText: '准备中',
      totalCount: 0,
      processedCount: 0,
      successCount: 0,
      failureCount: 0,
      currentProcessing: '',
      taskId: ''
    };
    progressVisible.value = true;
    
    return autoAnalyzeAllTopics();
  }).then(response => {
    if (response.code === 200 && response.data && response.data.taskId) {
      // 保存任务ID并开始轮询进度
      progressData.value.taskId = response.data.taskId;
      startProgressPolling();
    } else {
      // 如果没有返回taskId，说明没有需要处理的内容或者出错了
      // 直接显示结果并重置状态
      progressVisible.value = false; // 关闭进度对话框
      finishAnalysis(response);
    }
  }).catch(error => {
    // 出错时也要关闭进度对话框并重置状态
    progressVisible.value = false;
    finishAnalysis({
      code: 500,
      msg: error.message || '分析失败',
      data: null
    });
  });
};

// 开始轮询进度
const startProgressPolling = () => {
  canStop.value = true; // 允许停止
  // 清除可能存在的定时器
  if (progressTimer.value) {
    clearInterval(progressTimer.value);
  }
  
  // 设置轮询间隔（每秒查询一次）
  progressTimer.value = setInterval(() => {
    if (!progressData.value.taskId) {
      clearInterval(progressTimer.value);
      return;
    }
    
    getAnalysisProgress(progressData.value.taskId).then(response => {
      if (response.code === 200) {
        const data = response.data;
        // 更新进度数据
        progressData.value.totalCount = data.totalCount || 0;
        progressData.value.processedCount = data.processedCount || 0;
        progressData.value.successCount = data.successCount || 0;
        progressData.value.failureCount = data.failureCount || 0;
        progressData.value.currentProcessing = data.currentProcessing || '';
        progressData.value.percentage = data.progressPercentage || 0;
        
        // 根据状态更新显示
        if (data.status === 'COMPLETED') {
          progressData.value.status = 'success';
          progressData.value.statusText = '已完成';
          stopProgressPolling();
          // 延迟关闭进度对话框，显示最终结果
          setTimeout(() => {
            progressVisible.value = false;
            finishAnalysis({
              code: 200,
              msg: '分析完成！',
              data: {
                totalCount: data.totalCount,
                successCount: data.successCount,
                failCount: data.failureCount,
                duration: data.duration || 0
              }
            });
          }, 1000);
        } else if (data.status === 'ERROR') {
          progressData.value.status = 'exception';
          progressData.value.statusText = '错误';
          stopProgressPolling();
          // 延迟关闭进度对话框，显示错误信息
          setTimeout(() => {
            progressVisible.value = false;
            finishAnalysis({
              code: 500,
              msg: data.errorMessage || '分析出错',
              data: {
                totalCount: data.totalCount,
                successCount: data.successCount,
                failCount: data.failureCount,
                duration: data.duration || 0
              }
            });
          }, 1000);
        } else {
          progressData.value.status = '';
          progressData.value.statusText = '处理中';
        }
      } else {
        // 查询进度失败
        progressData.value.status = 'exception';
        progressData.value.statusText = '查询进度失败';
      }
    }).catch(() => {
      progressData.value.status = 'exception';
      progressData.value.statusText = '查询进度失败';
    });
  }, 1000);
};

// 停止轮询进度
const stopProgressPolling = () => {
  if (progressTimer.value) {
    clearInterval(progressTimer.value);
    progressTimer.value = null;
  }
};

// 完成分析并显示结果
const finishAnalysis = (response) => {
  analyzing.value = false;
  canStop.value = false; // 不允许停止
  isMinimized.value = false; // 重置最小化状态
  analysisResult.value = {
    success: response.code === 200,
    message: response.code === 200 ? '分析完成！' : response.msg || '分析失败',
    data: response.data
  };
  analysisVisible.value = true;
  getList();
};

// 组件卸载时清除定时器
onBeforeUnmount(() => {
  stopProgressPolling();
});

const getFictionLevelText = (level) => {
  const levels = { 0: '基于事实', 1: '部分虚构', 2: '完全虚构' };
  return levels[level] || '未知';
};

const getGenerationStatusText = (status) => {
  const statusMap = { 0: '未处理', 1: '生成成功', 2: '生成失败' };
  return statusMap[status] || '未知';
};

const handleMinimize = () => {
  isMinimized.value = true;
  progressVisible.value = false;
  // 显示最小化提示
  proxy.$message.info('分析正在后台进行，可点击"AI自动分析"按钮查看进度');
};

// 停止分析
const handleStopAnalysis = () => {
  proxy.$modal.confirm('确定要停止当前分析任务吗？').then(() => {
    // 调用后端停止接口
    return stopAnalysisTask(progressData.value.taskId);
  }).then(() => {
    // 停止前端轮询
    stopProgressPolling();
    // 重置状态
    analyzing.value = false;
    progressVisible.value = false;
    isMinimized.value = false;
    
    proxy.$message.success('分析任务已停止');
  }).catch(error => {
    const errorMsg = error?.message || error?.msg || '停止任务失败';
    proxy.$message.error('停止任务失败: ' + errorMsg);
  });
};

// 检查是否有最小化的任务正在运行
const checkMinimizedTask = () => {
  if (isMinimized.value && progressData.value.taskId) {
    // 恢复进度对话框
    progressVisible.value = true;
    isMinimized.value = false;
    return true;
  }
  return false;
};

const getAnalyzeButtonText = () => {
  if (isMinimized.value) {
    return '查看进度';
  }
  return analyzing.value ? '分析中...' : 'AI自动分析';
};

// 初始化
getList();
</script>

<style scoped>
.content-box {
  max-height: 200px;
  overflow-y: auto;
  padding: 10px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #f9f9f9;
  white-space: pre-wrap;
  word-break: break-all;
}

.progress-container {
  padding: 20px;
}

.progress-info {
  margin-top: 20px;
  line-height: 1.8;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.dialog-header-buttons {
  display: flex;
  gap: 5px;
}

.dialog-header-buttons .el-button {
  padding: 5px;
  margin: 0;
}
</style>